// (c) 2007, Stephane Alnet
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

function _hide_item(item)
{
    item.style.display = 'none';
    // item.style.visibility = 'hidden';
}

function _show_item(item)
{
    item.style.display = 'block';
    // item.style.visibility = 'visible';
}


function _disable_item(item)
{
    if(item.disabled) return;

    if(item.tagName == 'DIV')
    {
        _hide_item(item);
    }
    if(item.tagName == 'OPTION')
    {
        item.selected = false; // for OPTION
    }
    item.disabled = true; // for INPUT, SELECT, OPTION, etc.
}

function _enable_item(item)
{
    if(!item.disabled) return;

    if(item.tagName == 'DIV')
    {
        _show_item(item);
    }
    item.disabled = false; // for INPUT, SELECT, OPTION, etc.
}

function _enable_item_with_default(item)
{
    if(!item.disabled) return;

    _enable_item(item);
    if(item.attributes.is_default) // can be added to OPTION
    {
        item.defaultSelect = true;
        item.selected = true; 
        item.parentNode.value = item.value;
        item.parentNode.selectedIndex = item.index;
    };
}

// __update is a generic function that handles value updates.
function __update(w,value,enable_function)
{
    var name = w.name;
    var current_value = w.current_value;

    if(! name || ! value || (current_value && current_value == value))
    {
        return
    }

    var the_query = '[' + name + '~="' + value + '"]';
    // Disable non-matching ones
    dojo.query("["+name+"]:not("+the_query+")").forEach(_disable_item);
    // Enable the matching ones
    dojo.query(the_query).forEach(enable_function);
}

// _update is triggered when the end-user manipulates the form.
function _update(w)
{
    var value     = w.value;
    
    // Handle checkboxes.
    if(w.type == 'checkbox' && !w.checked)
    {
        value = '_';
    }

    __update(w,value,_enable_item_with_default);
}

function _install_update(item)
{
    dojo.connect(item,'onclick',function(evt) { _update(item) });
    dojo.connect(item,'onchange',function(evt) { _update(item) });
    // dojo.connect(item,'onValueChange',function(evt) { _update(item) });
    // dojo.connect(item,'selectOption',function(evt) { _update(item) });
    // dojo.connect(item,'onPressed',function(evt) { _update(item) });
}

function _install_update_onload()
{
    dojo.query('.trigger').forEach(_install_update);
}

dojo.addOnLoad(_install_update_onload);


// JSON handling

function _set_checkbox_value(item,value)
{
    // Taken from dojo...
    if(dojo.isIE){
        if(value){ item.setAttribute('checked', 'checked'); }
		else{ item.removeAttribute('checked'); }
	}else{
        if(value)
        {
            item.attributes.checked = 'checked';
            item.checked = true;
        }
        else
        {
            item.attributes.removeNamedItem('checked');
            item.checked = false;
        }
    }
}

function _set_select_value(item,value)
{
    item.value = value;
    for( var o in item.options)
    {
        if(o.value == value)
        {
            item.selectedIndex = o.index;
            o.selected = true;
            o.defaultSelect = true;
        }
        else
        {
            o.selected = false;
            o.defaultSelect = false;
        }
    }
}

function _set_value(the_form,name,value)
{
    // Note: we assume that all form elements have unique
    //       IDs that are equal to their names.
    //      (They do in the HTML we generate or provide.)

    item = dojo.byId(name);
    if(!item)
    {
        // XXX Remove log for production
        console.log(name+" is not a valid ID.");
        return;
    }

    if(item.tagName == 'INPUT')
    {
        if(item.attributes.type == 'checkbox')
        {
            _set_checkbox_value(item,value);
        }
        else
        {
            item.value = value;
        }
    }
    if(item.tagName == 'SELECT')
    {
        _set_select_value(item,value);
    }
}

function loading_done()
{
    dojo.query('.trigger').forEach(_update);
    dojo.query('#the_status').forEach(_hide_item);
}

// Populate a form based on JSON data in the URI
function populate_form(the_form,the_uri)
{
    if( ! the_uri )
    {
        loading_done();
        return;
    }
    dojo.xhrGet({
        url: the_uri,
        handleAs: 'json',
        timeout: 5000,
        load: function(response,ioArgs) {
            // use the JSON inside response to populate the fields
            for( var x in response )
            {
                _set_value(the_form,x,response[x]);
            }
            loading_done();
        },
        error: function(response,ioArgs) {
            console.log("HTTP status code: ", ioArgs.xhr.status);
            loading_done();
            return response;
        },
    });
}

// Submit a form to the URI
function submit_form(the_form,the_uri)
{
    if( ! the_uri ) return;
    dojo.xhrGet({
        url: the_uri,
        handleAs: 'json',
        timeout: 5000,
        load: function(response,ioArgs) {
            // use the JSON inside response to re-populate the fields?
        },
        error: function(response,ioArgs) {
            console.log("HTTP status code: ", ioArgs.xhr.status);
            return response;
        },
        form: the_form // submit this form!
    });
}

